package khleuven.mondzorg.domain;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.util.Base64;

public class BlobLib {

	public static String getIllustrationEncodedBlob(String link) throws DomainException {
		byte[] blob  = getIllustrationBlob(link);
		return Base64.encodeToString(blob, Base64.DEFAULT);
	}

	public static byte[] getIllustrationBlob(String link) throws DomainException {
		byte[] blob = new byte[0];
		DefaultHttpClient mHttpClient = new DefaultHttpClient();
		HttpGet mHttpGet = new HttpGet(link);
		HttpResponse mHttpResponse;
		try {
			mHttpResponse = mHttpClient.execute(mHttpGet);
	    	if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	      	  HttpEntity entity = mHttpResponse.getEntity();
	      	    if ( entity != null) {
	      	    	blob = EntityUtils.toByteArray(entity);
	      	    } else {
		      		throw new DomainException("Error retrieving "+link+" with no mHttpResponse");
		      	}
	      	} else {
	      		throw new DomainException("Error retrieving "+link+" with error "+mHttpResponse.getStatusLine().getStatusCode());
	      	}
		} catch (ClientProtocolException e) {
			throw new DomainException("ClientProtocolException Unable to retrieve image "+link, e);
		} catch (IOException e) {
			throw new DomainException("IOException Unable to retrieve image "+link, e);
		}
		
		return blob;
	}
}
